import re
from typing import Dict, Any, Optional
from pathlib import Path


class ConfigLoaderModule:
    """配置加载模块 - 加载和解析.config文件"""

    @staticmethod
    def parse_dot_config(file_path: str) -> Dict[str, Any]:
        """
        解析.config文件

        Args:
            file_path: .config文件路径

        Returns:
            配置值字典 {config_name: value}
        """
        config_values = {}

        try:
            with open(file_path, "r", encoding="utf-8") as f:
                for line_num, line in enumerate(f, 1):
                    line = line.strip()

                    # 跳过空行和注释
                    if not line or line.startswith("#"):
                        continue

                    # 解析配置行
                    match = re.match(r"^CONFIG_(\w+)=(.*)$", line)
                    if match:
                        config_name = match.group(1)
                        value_str = match.group(2).strip()

                        # 解析值
                        value = ConfigLoaderModule._parse_value(value_str)
                        config_values[config_name] = value

            return config_values
        except Exception as e:
            print(f"Failed to parse .config file: {e}")
            return {}

    @staticmethod
    def _parse_value(value_str: str) -> Any:
        """
        解析配置值

        Args:
            value_str: 字符串形式的值

        Returns:
            解析后的值
        """
        if not value_str:
            return None

        # 处理布尔值
        if value_str.lower() in ["y", "yes", "true", "1"]:
            return True
        elif value_str.lower() in ["n", "no", "false", "0"]:
            return False

        # 处理字符串（带引号）
        if (value_str.startswith('"') and value_str.endswith('"')) or (
            value_str.startswith("'") and value_str.endswith("'")
        ):
            return value_str[1:-1]

        # 处理整数
        if value_str.isdigit():
            return int(value_str)

        # 处理十六进制
        if value_str.startswith("0x") or value_str.startswith("0X"):
            try:
                return int(value_str, 16)
            except ValueError:
                pass

        # 处理其他类型
        return value_str

    @staticmethod
    def find_dot_config(start_dir: str = ".") -> Optional[str]:
        """
        在目录树中查找.config文件

        Args:
            start_dir: 起始目录

        Returns:
            .config文件路径或None
        """
        start_path = Path(start_dir).resolve()

        # 在当前目录和父目录中查找
        current_dir = start_path
        while True:
            dot_config_path = current_dir / ".config"
            if dot_config_path.exists() and dot_config_path.is_file():
                return str(dot_config_path)

            parent_dir = current_dir.parent
            if parent_dir == current_dir:  # 到达根目录
                break

            current_dir = parent_dir

        return None

    @staticmethod
    def load_config_from_file(file_path: str) -> Dict[str, Any]:
        """
        从文件加载配置

        Args:
            file_path: 配置文件路径

        Returns:
            配置值字典 {config_name: value}
        """
        file_ext = Path(file_path).suffix.lower()

        if file_ext == ".config":
            return ConfigLoaderModule.parse_dot_config(file_path)
        else:
            # 可以扩展支持其他格式
            raise ValueError(f"Unsupported file format: {file_ext}")

    @staticmethod
    def merge_configs(
        base_config: Dict[str, Any], new_config: Dict[str, Any], overwrite: bool = True
    ) -> Dict[str, Any]:
        """
        合并两个配置字典

        Args:
            base_config: 基础配置
            new_config: 新配置
            overwrite: 是否覆盖现有配置

        Returns:
            合并后的配置
        """
        merged_config = base_config.copy()

        for key, value in new_config.items():
            if overwrite or key not in merged_config:
                merged_config[key] = value

        return merged_config
